import os

import django
from django.utils import timezone

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
from django.contrib.auth.models import User
from Fantasy.models import Media
from django.core.files import File


def bulk_create():
    username = range(1002, 1030)
    password = ['123456' for i in range(28)]

    for u, p in zip(username, password):
        user = User.objects.create_user(username=u, password=p)
        user.first_name = '用户'
        user.groups.add(1)
        user.is_staff = True
        user.last_login = timezone.now()
        user.save()


def size(path):
    __size = os.path.getsize(path)
    __size = __size / float(1024 * 1024)

    return round(__size, 2)


def bulk_upload(dirpath):
    myfile, __file = None, None

    items = list()
    path_list = list(os.scandir(dirpath))
    for i in path_list:
        if os.path.isfile(i):
            file_size = size(i)
            file_name = os.path.basename(i).split('.')[-2]
            __file = open(i, mode='rb')
            myfile = File(__file, name=os.path.basename(i))

            source = Media(title=file_name, file_size=file_size, file=myfile, pub_date=timezone.now(),
                           category='其他资料')
            items.append(source)

    Media.objects.bulk_create(items)
    myfile.close()
    __file.close()


bulk_upload(r"D:\化学复习资料\食品化学PPT")
